package com.chen.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Result;
import com.chen.mapper.InfoMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.Files;
import com.chen.pojo.Info;
import com.chen.pojo.User;
import com.chen.service.Impl.InfoServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author chen
 */
@RestController
@RequestMapping("/info")
@Api(value = "InfoController", tags = "登录信息")
public class InfoController {
    @Resource
    private UserMapper userMapper;

    @Resource
    private InfoMapper infoMapper;

    @Autowired
    private InfoServiceImpl infoService;

    //    查询所有信息
    @GetMapping("/finadAllInfo")
    public Result findAllInfo() {
        return infoService.findAllInfo();
    }

    //    分页查询
    @GetMapping("/page")
    public IPage<Info> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String nickname) {
        IPage<Info> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Info> queryWrqpper = new QueryWrapper<>();

        List<Info> infos = selectAvatar();

        if (!"".equals(username)) {
            queryWrqpper.like("username", username);
        }
        if (!"".equals(nickname)) {
            queryWrqpper.like("nickname", nickname);
        }


        IPage<Info> userPage = infoService.page(page, queryWrqpper);
        return userPage;

    }

    @GetMapping("/setAvatar")
    public Result setAvatar() {
        List<Info> infos = selectAvatar();
        return Result.success(infos);
    }

    public List<Info> selectAvatar() {
        List<Info> infoList = infoService.list();
        for (Info info : infoList) {
            User one = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, info.getUsername()));
            if (ObjectUtil.isNotEmpty(one)) {
                if (StrUtil.isBlank(info.getNickname())) {
                    info.setNickname(one.getNick());
                }
                if (StrUtil.isBlank(info.getAvatar())) {
                    info.setAvatar(one.getAvatar());
                } else {
                    info.setAvatar("https://img2.baidu.com/it/u=2906052251,1830965798&fm=26&fmt=auto");
                }
            }
        }
        return infoList;
    }


    //    删除
    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        return infoService.removeById(id);
    }



    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Info> list = infoService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("addr", "登录地址");
        writer.addHeaderAlias("ip", "登录ip");
        writer.addHeaderAlias("type", "浏览器类型");
        writer.addHeaderAlias("time", "创建时间");
        writer.addHeaderAlias("last_time", "上次登录时间");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("登录信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }


    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        // select * from sys_file where id in (id,id,id...)
        QueryWrapper<Info> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        return Result.success( infoService.removeByIds(ids));
    }

    @PutMapping("/updateEbale")
    public Result updateEable(@RequestBody Info info){

        return Result.success(infoService.updateById(info));
    }

    @PostMapping("/insertInfo")
    public Result insertInfo(@RequestBody Info info){

        return Result.success(infoService.save(info));
    }

}
